package com.hmall.gateway.filter;

import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.util.JwtTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author wangyoucheng
 * @date 2025/9/2
 * @description TOD0
 */
@Slf4j
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    private AuthProperties authProperties;

    @Autowired
    private JwtTool jwtTool;


    private AntPathMatcher antPathMatcher= new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.如果本次请求路径在白名单里：直接放行
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        List<String> excludePaths = authProperties.getExcludePaths();
        //判断本次请求是否在白名单中，在的话就放行，不拦截
        for (String excludePath : excludePaths) {
            if (antPathMatcher.match(excludePath,path)) {
                return chain.filter(exchange);
            }
        }
        //2.获取请求携带的令牌,如果没有令牌返回401
        String token = request.getHeaders().getFirst("Authorization");
        if (token == null || "".equals(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //解析令牌 如果出错，返回401
        Long userId;
        try {
             userId = jwtTool.parseToken(token);
        } catch (Exception e) {
            log.error("解析令牌失败");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //得到当前用户id，添加到请求头上
        request.mutate().header("user-info",userId.toString());

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
